package main

import (
	"fmt"
	"io"
	"net/http"
	"os"
)

func downloadFile(url, filename string) {
	r, err := http.Get(url)
	if err != nil {
		panic(err)
	}
	defer func() { _ = r.Body.Close() }()

	f, err := os.Create(filename)
	if err != nil {
		panic(err)
	}
	defer func() { _ = f.Close() }()

	n, err := io.Copy(f, r.Body)

	fmt.Println(n, err)
}

type Reader struct {
	io.Reader
	FileName string
	Totol    int64
	Current  int64
}

func (r *Reader) Read(p []byte) (n int, err error) {
	n, err = r.Reader.Read(p)

	r.Current += int64(n)

	fmt.Printf("\r下载到本地文件名%s\t\t进度 %.2f%%",
		r.FileName, float64(r.Current*10000/r.Totol)/100)
	fmt.Printf("[")
	for i := 0; i < int(r.Current*100/r.Totol)/3; i++ {
		fmt.Printf("=")
	}
	if r.Current != r.Totol {
		fmt.Printf(">")
	}
	for i := int(r.Current*100/r.Totol) / 3; i < 100/3; i++ {
		fmt.Printf(" ")
	}
	fmt.Printf("]")
	return
}

func DownloadFileProgress(url, filename string) {
	r, err := http.Get(url)
	if err != nil {
		panic(err)
	}
	defer func() { _ = r.Body.Close() }()

	f, err := os.Create(filename)
	if err != nil {
		panic(err)
	}
	defer func() { _ = f.Close() }()

	reader := &Reader{
		Reader:   r.Body,
		Totol:    r.ContentLength,
		FileName: filename,
	}

	_, _ = io.Copy(f, reader)

	fmt.Println()
}

func main() {
	// 自动文件下载，比如自动下载图片、压缩包
	url := "https://makedown-save.oss-cn-beijing.aliyuncs.com" +
		"/Snipaste_2019-11-21_10-15-30.png"
	url1 := "https://gligli-oss.oss-cn-qingdao.aliyuncs.com/yys.mp4"
	filename := "string.png"
	filename1 := "yys.mp4"
	DownloadFileProgress(url, filename)
	DownloadFileProgress(url1, filename1)
}
